package app.web.admin.domain.ao;

import app.config.Config;
import app.web.admin.mapper.AdminMapper;
import com.gitee.feizns.dynamic.bean.Convertible;
import com.gitee.feizns.quickstart.validation.Verifiable;
import com.gitee.feizns.quickstart.validation.constraints.DynamicValidate;
import com.gitee.feizns.quickstart.validation.constraints.Phone;
import com.gitee.feizns.quickstart.web.decrypt.DecryptionAlgorithm;
import com.gitee.feizns.quickstart.web.ex.BadRequestException;
import lombok.Data;
import org.hibernate.validator.constraints.URL;
import org.springframework.util.StringUtils;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;


/**
 * 管理员创建参数
 * @author feizns
 * @since 2025-04-09
 */
@Data
@DynamicValidate
public class UserCreateAo implements Convertible, Verifiable {

    /**
     * 用户名称
     */
    @NotBlank(message = "用户名称不能为空.")
    private String name;

    /**
     * 头像
     */
    @URL(message = "头像格式不合法.")
    @NotBlank(message = "头像不能为空.")
    private String avatar = Config.defaultAvatarUrl();

    /**
     * 手机号码
     */
    @Phone(message = "手机号格式不合法.")
    @NotBlank(message = "手机号不能为空.")
    private String mobile;

    /**
     * 职位
     */
    private String title;

    /**
     * 邮箱
     */
    @Email(message = "邮箱格式不合法.")
    private String email;

    /**
     * 角色编号列表
     */
    @NotNull(message = "角色编号列表不能为空.")
    private List<Long> roleIds = new ArrayList<>();

    /**
     * 密码
     */
    @NotBlank(message = "密码不能为空.")
    private String password;

    @Override
    public boolean validate() {
        if ( Config.rsaAutomaticDecryption() ) {
            this.mobile = DecryptionAlgorithm.instance().decrypt(mobile);
            this.password = DecryptionAlgorithm.instance().decrypt(password);
        }
        if ( StringUtils.hasText(mobile) && AdminMapper.existsMobile(mobile) )
            throw new BadRequestException("手机号['%s']已存在.".formatted(mobile));
        if ( StringUtils.hasText(email) && AdminMapper.existsEmail(email) )
            throw new BadRequestException("邮箱['%s']已存在.".formatted(email));
        return Verifiable.super.validate();
    }

}
